package com.qdxwx.web.controller.auth;

import com.qdxwx.common.cache.CacheUtils;
import com.qdxwx.common.constants.CacheConstants;
import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.common.utils.TKString;
import com.qdxwx.data.service.user.UserService;
import com.qdxwx.models.enums.UserRegisterFrom;
import com.qdxwx.models.user.User;
import com.qdxwx.models.user.UserToken;
import com.qdxwx.web.controller.BaseController;
import com.qdxwx.web.utils.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * @author ZhiYong
 */
@Controller
@RequestMapping("/auth")
public class RegisterController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(RegisterController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/register.html")
    public String registerForm(HttpServletRequest request) {
        long userId = LoginUser.getUserId(request);
        if (userId > 0) {
            return "redirect:/user/index.html";
        }
        return getViewPath("auth/register");
    }

    /**
     * 创建用户
     */
    @RequestMapping("/register/create.json")
    @ResponseBody
    public AjaxResult createUser(HttpServletRequest request, HttpServletResponse response) {
        //获得输入的手机验证码
        String mobileCode = TKString.trim(request.getParameter("mobileCode"));
        String mobile = TKString.trim(request.getParameter("mobile"));
        String userName = TKString.trim(request.getParameter("userName"));
        String password = TKString.trim(request.getParameter("password"));


        if (!TKString.isMobile(mobile)) {
            return AjaxResult.error("手机格式不正确，请重新输入！");
        }
        if (!TKString.isName(userName)) {
            return AjaxResult.error("姓名格式不正确，只能输入中文、英文、数字及下划线，不能有特殊字符！");
        }
        if (mobileCode.length() < 6) {
            return AjaxResult.error("请输入手机验证码");
        }
        if (password.length() == 0 || !TKString.isPassword(password)) {
            return AjaxResult.error("密码有字母和数字组合且≥6位≤16位");
        }
        //从缓存提取手机验证码
        String mobileCodeNum = (String) CacheUtils.get(CacheConstants.MOBILE_SMS_PRE + mobile);
        if (!mobileCode.equals(mobileCodeNum)) {
            return AjaxResult.error("请输入正确的手机验证码");
        }

        //request.getSession().removeAttribute(UserConstants.randCode);
        //查看手机号是否已注册
        if (userService.isExistMobile(mobile)) {
            return AjaxResult.error("该手机号已被使用");
        }

        User user = new User();
        user.setMobile(mobile);
        user.setUserName(userName);
        user.setPassword(password);
        user.setRegisterFrom(UserRegisterFrom.get(request));

        //try {
        long userId = userService.register(request, user);

        if (userId < 1) {
            return AjaxResult.error("注册用户失败，请重试！");
        }

        UserToken token = userService.doLogin(request, user);
        LoginUser.setUser(request, user);
        LoginUser.setCookie(response, token);
        //这里设置用户信息
        return AjaxResult.success(userId);
        //} catch (Exception e) {
        //    logger.error("createUser-error", e);
        //    return setJson(false, e.getMessage());
        //}
    }

    /**
     * 创建用户
     */
    @RequestMapping("/register/exist.json")
    @ResponseBody
    public AjaxResult existUser(HttpServletRequest request) {
        String mobile = TKString.trim(request.getParameter("mobile"));
        //获得输入的手机验证码
        if (!TKString.isMobile(mobile)) {
            return AjaxResult.error("手机格式不正确，请重新输入！");
        }
        //查看手机号是否已注册
        if (userService.isExistMobile(mobile)) {
            return AjaxResult.error("该手机号已被使用");
        }

        return AjaxResult.success();
        //} catch (Exception e) {
        //    logger.error("createUser-error", e);
        //    return setJson(false, e.getMessage());
        //}
    }
}
